package com.mxy.myapplication.asynctask;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.mxy.myapplication.pojo.DownloadMissionPojo;
import com.mxy.myapplication.util.DownloadMissionManageUtil;
import com.mxy.myapplication.util.HttpUrlConnectionutil;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.lang.ref.WeakReference;
import java.net.URL;

public class AsyncTaskForDownloadFile extends AsyncTask<Void, Void, Void> {

    private DownloadMissionPojo downloadMissionPojo;
    private WeakReference<Handler> handlerWeakReference;

    public AsyncTaskForDownloadFile(DownloadMissionPojo downloadMissionPojo, Handler handler) {
        this.downloadMissionPojo = downloadMissionPojo;
        this.handlerWeakReference = new WeakReference<>(handler);
    }


    @Override
    protected Void doInBackground(Void... voids) {

        try {
            URL url = new URL(this.downloadMissionPojo.getFileUrl());
            InputStream is = HttpUrlConnectionutil.getHttpUrlConnectionBreakPoint(url,
                    downloadMissionPojo);
            if (is != null) {
                File file = new File(this.downloadMissionPojo.getFilePath().substring(0,
                        this.downloadMissionPojo.getFilePath().lastIndexOf(File.separator) + 1));
                if (!file.exists()) {
                    file.mkdirs();
                }
                file = new File(this.downloadMissionPojo.getFilePath());
                if (!file.exists()) {
                    file.createNewFile();
                }

                //输入
                BufferedInputStream bis = new BufferedInputStream(is);
                //输出
                RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
                //开始写入
                int size = 0;

                //缓存不宜设置得过大
                byte[] buffer = new byte[1024];

                //起始时间
                long beginTime = System.currentTimeMillis();
                //累计读取的数据量
                int readSizeCount = 0;
                while (downloadMissionPojo.getDownloadState() == DownloadMissionPojo.DOWNLOADSTATE_DOWNLOADING && ((size = bis.read(buffer)) != -1)) {
                    //双重判断 避免输入流阻塞时用户暂停任务
                    if (downloadMissionPojo.getDownloadState() == DownloadMissionPojo.DOWNLOADSTATE_DOWNLOADING) {
                        randomAccessFile.seek(downloadMissionPojo.getReadSize());
                        randomAccessFile.write(buffer, 0, size);
                        //保存已读取数据
                        downloadMissionPojo.setReadSize(downloadMissionPojo.getReadSize() + size);
                        //累加读取数量
                        readSizeCount = readSizeCount + size;
                        //每三秒发送一次数据
                        Handler handler;
                        long endTime = System.currentTimeMillis();
                        if (endTime - beginTime >= (1000 * DownloadMissionManageUtil.MISSION_REFRESH_TIME_INTERVAL) && ((handler = this.handlerWeakReference.get()) != null)) {
                            beginTime = endTime;
                            downloadMissionPojo.setDownloadSpeed(readSizeCount);
                            readSizeCount = 0;
                            Message message = new Message();
                            message.obj = downloadMissionPojo;
                            message.setTarget(handler);
                            message.sendToTarget();
                        }
                    }
                }
                randomAccessFile.close();
                bis.close();
                is.close();
                downloadMissionPojo.setDownloadSpeed(0);
                Handler handler;
                //下载完毕
                if (size == -1 && ((handler = this.handlerWeakReference.get()) != null)) {
                    Message message = new Message();
                    message.obj = downloadMissionPojo;
                    message.setTarget(handler);
                    message.sendToTarget();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}